//
//  LoginViewController.m
//  SelfDriving
//
//  Created by apple on 16/1/7.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "LoginViewController.h"
#import "BusinessService+User.h"
#import "RegisterSViewController.h"
#import "XHWResetPwdCtrl.h"
@interface LoginViewController ()<UIAlertViewDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIView *pdview;
@property (weak, nonatomic) IBOutlet UIView *userview;
@property (weak, nonatomic) IBOutlet UIView *d3fview;
@property (weak, nonatomic) IBOutlet UIButton *rbtn;
@property (weak, nonatomic) IBOutlet BaseTextField *phoneField;
@property (weak, nonatomic) IBOutlet BaseTextField *pwdField;
@property (weak, nonatomic) IBOutlet UIImageView *loginImg;
@property (weak, nonatomic) IBOutlet UIButton *qqLoginBtn;
@property (weak, nonatomic) IBOutlet UIButton *weixinLoginBtn;

@end

@implementation LoginViewController
{
    NSString * oldPhoneNum;  //xhw11月20号加
}

//用户账号设置了头像，只有没有清空账号，用户的头像都要显示出来，清空账号后或者用户没有设置头像的才用默认头像(xhw11月20号加)
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSLog(@"%@", string);
    if (textField.text.length == 11 && ![string isEqualToString:@""]) {
        [textField.text stringByReplacingCharactersInRange:range withString:@""];
        return NO;
    }
    NSString * newStr = [NSString stringWithFormat:@"%@%@",textField.text,string];
    if ([newStr isEqualToString:oldPhoneNum]) {
        if (range.location == 10 && [string isEqualToString:@""]) {
            [ValidateHelper setImage:@"" img:_loginImg istoux:YES];
            _loginImg.layer.cornerRadius = 0;
            _loginImg.clipsToBounds = YES;
        }
        else {
            NSString *imgURL = [[UserDefaults readUserDefaultObjectValueForKey:@"ruser"] objectForKey:@"headsmall"];
            if (imgURL) {
                [ValidateHelper setImage:imgURL img:_loginImg istoux:YES];
                _loginImg.layer.cornerRadius = _loginImg.frame.size.width/2;
                _loginImg.clipsToBounds = YES;
            }else{
                _loginImg.layer.cornerRadius = 0;
                _loginImg.clipsToBounds = YES;
            }
            [ValidateHelper setImage:imgURL img:_loginImg istoux:YES];
            _loginImg.layer.cornerRadius = _loginImg.frame.size.width/2;
            _loginImg.clipsToBounds = YES;
        }
    }

    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _userview.backgroundColor=[UIColorBlack colorWithAlphaComponent:0.3];
    _pdview.backgroundColor=[[UIColor blackColor] colorWithAlphaComponent:0.3];
    //xhw11月20号加
    _phoneField.delegate = self;
    
    _rbtn.layer.borderColor = UIColorMakeWithHex(@"A7F590").CGColor;
    _rbtn.layer.borderWidth = 1;
    _rbtn.layer.cornerRadius = 4;
    if ([UserDefaults readUserDefaultObjectValueForKey:@"ruser"]) {
        _phoneField.text = [[UserDefaults readUserDefaultObjectValueForKey:@"ruser"] objectForKey:@"phone"];
        oldPhoneNum = _phoneField.text;//xhw11月20号加
        NSString *imgURL = [[UserDefaults readUserDefaultObjectValueForKey:@"ruser"] objectForKey:@"headsmall"];
        if (imgURL) {
            [ValidateHelper setImage:imgURL img:_loginImg istoux:YES];
            _loginImg.layer.cornerRadius = _loginImg.frame.size.width/2;
            _loginImg.clipsToBounds = YES;
        }else{
            _loginImg.layer.cornerRadius = 0;
            _loginImg.clipsToBounds = YES;
        }
        
    }
}
-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = YES;
    
    BOOL isInstallQQ = [[UMSocialManager defaultManager] isInstall:UMSocialPlatformType_QQ];
    if (isInstallQQ) {
        _qqLoginBtn.hidden = NO;
    }
    else {
        _qqLoginBtn.hidden = YES;
    }
    
    BOOL isInstallWeixin = [[UMSocialManager defaultManager] isInstall:UMSocialPlatformType_WechatSession];
    if (isInstallWeixin) {
        _weixinLoginBtn.hidden = NO;
    }
    else {
        _weixinLoginBtn.hidden = YES;
    }
    
    
}

- (IBAction)resetPwdAction:(UIButton *)sender {
    UIStoryboard * customerStoryboard = [UIStoryboard storyboardWithName:@"U" bundle:[NSBundle mainBundle]];
    UIViewController *resetPwdCtrl = [customerStoryboard instantiateViewControllerWithIdentifier:@"resetPwdVC"];

    [self.navigationController pushViewController:resetPwdCtrl animated:YES];
    //resetPwdVC
}


- (IBAction)toRegister:(UIButton *)sender {
    
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"U"
                                                                 bundle:[NSBundle mainBundle]];
    UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"RegisterVC"];
    [self.navigationController pushViewController:searchResultDetailController animated:YES];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
- (IBAction)loginAction:(UIButton *)sender {
    //    [[AppDelegate shareDelegate] initbar];
    
    if ([_phoneField.text trim].length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入账号"];
        return;
    }
    if ([_pwdField.text trim].length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入密码"];
        return;
    }
    BusinessService *servicer = [BusinessService shareInstance];
    NSMutableDictionary *dic = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
    [dic setObject:[_phoneField.text trim] forKey:@"phone"];
    [dic setObject:[_pwdField.text trim] forKey:@"password"];
    [dic setObject:[ValidateHelper getID] forKey:@"deviceid"];
    
    [SVProgressHUD showWithStatus:@"登录中..."];
    [servicer login:dic success:^(id result) {
        [SVProgressHUD dismiss];
        [UserDefaults clearUserDefaultWithKey:@"ymopenfire"];
        LoginResponseModel *user = result;
        [[AppDelegate shareDelegate]loginECLoginInfo:user.uid];
        if([user.code intValue] == -1){
            UIAlertView *customAlertView;
            if (customAlertView==nil) {
                customAlertView = [[UIAlertView alloc] initWithTitle:@"请输入验证码" message:user.msg delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            }
            [customAlertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
            UITextField *nameField = [customAlertView textFieldAtIndex:0];
            customAlertView.tag = 1024;
            nameField.tag = 1025;
            [customAlertView show];
            return ;
        }
        
        //xhw2018-2-11加:登录的时候也需要传wifi名字
        NSString *networkStr = [[AppDelegate shareDelegate] getNetWorkStates];
        if ([networkStr isEqualToString:@"wifi"]) {
            NSString *wifiStr = [ValidateHelper GetWifiName];
            NSMutableDictionary *userLocation = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
            [userLocation setObject:@"1" forKey:@"type"];
            [userLocation setObject:wifiStr forKey:@"wifi_ssid"];
            [[BusinessService shareInstance]updatewifi:userLocation success:^(id result) {
            } failure:^(id result) {
            }];
        }
        else {
            NSMutableDictionary *userLocation = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
            [userLocation setObject:@"0" forKey:@"type"];
            [[BusinessService shareInstance]updatewifi:userLocation success:^(id result) {
            } failure:^(id result) {
            }];
        }
        //xhw2018-2-11加
        [UserDefaults writeUserDefaultObjectValue:dic withKey:@"user"];//自动登录
        LoginResponseModel *model = result;
        [dic setObject:model.headsmall forKey:@"headsmall"];
        [UserDefaults writeUserDefaultObjectValue:dic withKey:@"ruser"];
        [AppDelegate shareDelegate].user = result;
        NSString *uid = [NSString stringWithFormat:@"%@",[AppDelegate shareDelegate].user.uid];
        [[AppDelegate shareDelegate] userDidLogin:uid pwd:[_pwdField.text trim]];
        [[AppDelegate shareDelegate] initbar];
        
        
    } failure:^(id result) {
        [SVProgressHUD showErrorWithStatus:result];
    }];
}

#pragma mark 登陆遇到登陆保护处理
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    UITextField *nameField = [alertView textFieldAtIndex:0];
  
    [nameField resignFirstResponder];
    if (buttonIndex == 1) {
        if ([nameField.text trim].length == 0) {
            [SVProgressHUD showErrorWithStatus:@"请输入验证码"];
            [alertView show];
            return;
        }
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        [dic setObject:[_phoneField.text trim] forKey:@"phone"];
        [dic setObject:[_pwdField.text trim] forKey:@"password"];
        [dic setObject:[ValidateHelper getID] forKey:@"deviceid"];
        [dic setObject:nameField.text forKey:@"code"];
        [SVProgressHUD showWithStatus:@"登录中..."];
        [[BusinessService shareInstance]login:dic success:^(id result) {
            [SVProgressHUD dismiss];
            [UserDefaults writeUserDefaultObjectValue:dic withKey:@"user"];//自动登录
            LoginResponseModel *model = result;
            [dic setObject:model.headsmall forKey:@"headsmall"];
            [UserDefaults writeUserDefaultObjectValue:dic withKey:@"ruser"];
            [AppDelegate shareDelegate].user = result;
            NSString *uid = [NSString stringWithFormat:@"%@",[AppDelegate shareDelegate].user.uid];
           
            [[AppDelegate shareDelegate]loginECLoginInfo:uid];

            [[AppDelegate shareDelegate] userDidLogin:uid pwd:[_pwdField.text trim]];
            [[AppDelegate shareDelegate] initbar];
        } failure:^(id result) {
            [SVProgressHUD showErrorWithStatus:result];
        }];
    }
}
#pragma mark第三方QQ登录
- (IBAction)QQloginAction:(id)sender {
    BOOL isInstallQQ = [[UMSocialManager defaultManager] isInstall:UMSocialPlatformType_QQ];
    if (isInstallQQ) {
        [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_QQ currentViewController:nil completion:^(id result, NSError *error) {
            if (error) {
                
            }else {
                UMSocialUserInfoResponse *resp = result;
                NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
                [dic setObject:@"1" forKey:@"type"];
                [dic setObject:resp.openid forKey:@"openid"];
                [dic setObject:resp.name forKey:@"nickname"];
                [dic setObject:resp.iconurl forKey:@"headsmall"];
                [[BusinessService shareInstance] login3:dic success:^(id result) {
                    LoginResponseModel *user = result;
                    if ([user.is_setting intValue] == 0) {
                        UIStoryboard * customerStoryboard = [UIStoryboard storyboardWithName:@"U" bundle:[NSBundle mainBundle]];
                        RegisterSViewController *searchResultDetailCtrl = [customerStoryboard instantiateViewControllerWithIdentifier:@"RegisterSVC"];
                        searchResultDetailCtrl.model = result;
                        [self.navigationController pushViewController:searchResultDetailCtrl animated:YES];
                        
                    }
                    else {
                        //xhw2018-2-11加:登录的时候也需要传wifi名字
                        NSString *networkStr = [[AppDelegate shareDelegate] getNetWorkStates];
                        if ([networkStr isEqualToString:@"wifi"]) {
                            NSString *wifiStr = [ValidateHelper GetWifiName];
                            NSMutableDictionary *userLocation = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
                            [userLocation setObject:@"1" forKey:@"type"];
                            [userLocation setObject:wifiStr forKey:@"wifi_ssid"];
                            [[BusinessService shareInstance]updatewifi:userLocation success:^(id result) {
                            } failure:^(id result) {
                            }];
                        }
                        else {
                            NSMutableDictionary *userLocation = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
                            [userLocation setObject:@"0" forKey:@"type"];
                            [[BusinessService shareInstance]updatewifi:userLocation success:^(id result) {
                            } failure:^(id result) {
                            }];
                        }
                        //xhw2018-2-11加
                        
                        [AppDelegate shareDelegate].user = user;
                        [[AppDelegate shareDelegate]loginECLoginInfo:user.uid];
                        NSString *uid = [NSString stringWithFormat:@"%@",[AppDelegate shareDelegate].user.uid];
                        [[AppDelegate shareDelegate] userDidLogin:uid pwd:user.openfire];
                        [[AppDelegate shareDelegate] initbar];
                        [UserDefaults writeUserDefaultObjectValue:dic withKey:@"ymopenfire"];
                    }
                } failure:^(id result) {
                    [SVProgressHUD showErrorWithStatus:result];
                }];
            }
        }];
    }
    else {
        [SVProgressHUD showInfoWithStatus:@"请安装最新版手机QQ，才能使用QQ账号登录"];
    }
}
#pragma mark 第三方微信登录
- (IBAction)WXloginAction:(id)sender {
    
    BOOL isInstallWeChat = [[UMSocialManager defaultManager] isInstall:UMSocialPlatformType_WechatSession];
    
    if (isInstallWeChat) {
        [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_WechatSession currentViewController:nil completion:^(id result, NSError *error) {
            if (error) {
                
            }else {
                UMSocialUserInfoResponse *resp = result;
                NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
                [dic setObject:@"1" forKey:@"type"];
                [dic setObject:resp.openid forKey:@"openid"];
                [dic setObject:resp.name forKey:@"nickname"];
                [dic setObject:resp.iconurl forKey:@"headsmall"];
                [[BusinessService shareInstance] login3:dic success:^(id result) {
                    LoginResponseModel *user = result;
                    if ([user.is_setting intValue] == 0) {
                        UIStoryboard * customerStoryboard = [UIStoryboard storyboardWithName:@"U" bundle:[NSBundle mainBundle]];
                        RegisterSViewController *searchResultDetailCtrl = [customerStoryboard instantiateViewControllerWithIdentifier:@"RegisterSVC"];
                        searchResultDetailCtrl.model = result;
                        [self.navigationController pushViewController:searchResultDetailCtrl animated:YES];
                    }
                    else {
                        //xhw2018-2-11加:登录的时候也需要传wifi名字
                        NSString *networkStr = [[AppDelegate shareDelegate] getNetWorkStates];
                        if ([networkStr isEqualToString:@"wifi"]) {
                            NSString *wifiStr = [ValidateHelper GetWifiName];
                            NSMutableDictionary *userLocation = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
                            [userLocation setObject:@"1" forKey:@"type"];
                            [userLocation setObject:wifiStr forKey:@"wifi_ssid"];
                            [[BusinessService shareInstance]updatewifi:userLocation success:^(id result) {
                            } failure:^(id result) {
                            }];
                        }
                        else {
                            NSMutableDictionary *userLocation = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
                            [userLocation setObject:@"0" forKey:@"type"];
                            [[BusinessService shareInstance]updatewifi:userLocation success:^(id result) {
                            } failure:^(id result) {
                            }];
                        }
                        //xhw2018-2-11加
                        
                        [AppDelegate shareDelegate].user = user;
                        [[AppDelegate shareDelegate]loginECLoginInfo:user.uid];
                        NSString *uid = [NSString stringWithFormat:@"%@",[AppDelegate shareDelegate].user.uid];
                        [[AppDelegate shareDelegate] userDidLogin:uid pwd:user.openfire];
                        [[AppDelegate shareDelegate] initbar];
                        [UserDefaults writeUserDefaultObjectValue:dic withKey:@"ymopenfire"];
                    }
                } failure:^(id result) {
                    [SVProgressHUD showErrorWithStatus:result];
                }];
            }
        }];
    }
    else {
        [SVProgressHUD showInfoWithStatus:@"请安装最新版手机微信，才能使用微信账号登录"];
    }
}
#pragma mark 第三方微博登录
- (IBAction)WBloginAction:(UIButton *)sender {
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_Sina currentViewController:nil completion:^(id result, NSError *error) {
        if (error) {
            
        }else {
            UMSocialUserInfoResponse *resp = result;
            NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
            [dic setObject:@"1" forKey:@"type"];
            [dic setObject:resp.accessToken forKey:@"openid"];
            [dic setObject:resp.name forKey:@"nickname"];
            [dic setObject:resp.iconurl forKey:@"headsmall"];
            [[BusinessService shareInstance] login3:dic success:^(id result) {
                LoginResponseModel *user = result;
                if ([user.is_setting intValue] == 0) {
                    UIStoryboard * customerStoryboard = [UIStoryboard storyboardWithName:@"U" bundle:[NSBundle mainBundle]];
                    RegisterSViewController *searchResultDetailCtrl = [customerStoryboard instantiateViewControllerWithIdentifier:@"RegisterSVC"];
                    searchResultDetailCtrl.model = result;
                    [self.navigationController pushViewController:searchResultDetailCtrl animated:YES];
                    
                }
                else {
                    
                    //xhw2018-2-11加:登录的时候也需要传wifi名字
                    NSString *networkStr = [[AppDelegate shareDelegate] getNetWorkStates];
                    if ([networkStr isEqualToString:@"wifi"]) {
                        NSString *wifiStr = [ValidateHelper GetWifiName];
                        NSMutableDictionary *userLocation = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
                        [userLocation setObject:@"1" forKey:@"type"];
                        [userLocation setObject:wifiStr forKey:@"wifi_ssid"];
                        [[BusinessService shareInstance]updatewifi:userLocation success:^(id result) {
                        } failure:^(id result) {
                        }];
                    }
                    else {
                        NSMutableDictionary *userLocation = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
                        [userLocation setObject:@"0" forKey:@"type"];
                        [[BusinessService shareInstance]updatewifi:userLocation success:^(id result) {
                        } failure:^(id result) {
                        }];
                    }
                    //xhw2018-2-11加
                    
                    [AppDelegate shareDelegate].user = user;
                    [[AppDelegate shareDelegate]loginECLoginInfo:user.uid];
                    NSString *uid = [NSString stringWithFormat:@"%@",[AppDelegate shareDelegate].user.uid];
                    [[AppDelegate shareDelegate] userDidLogin:uid pwd:user.openfire];
                    [[AppDelegate shareDelegate] initbar];
                    [UserDefaults writeUserDefaultObjectValue:dic withKey:@"ymopenfire"];
                }
            } failure:^(id result) {
                [SVProgressHUD showErrorWithStatus:result];
            }];
        }
    }];
    
   }


@end
